import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/task_model.dart';
import '../services/task_service.dart';

/// 任务列表状态管理
class TaskNotifier extends StateNotifier<List<TaskModel>> {
  TaskNotifier() : super([]) {
    loadTasks();
  }

  /// 加载所有任务
  void loadTasks() {
    state = TaskService.getAllTasks();
  }

  /// 添加新任务
  Future<void> addTask(TaskModel task) async {
    await TaskService.addTask(task);
    state = [...state, task];
  }

  /// 更新任务
  Future<void> updateTask(TaskModel updatedTask) async {
    await TaskService.updateTask(updatedTask);
    state = [
      for (final task in state)
        if (task.id == updatedTask.id) updatedTask else task,
    ];
  }

  /// 删除任务
  Future<void> deleteTask(String taskId) async {
    await TaskService.deleteTask(taskId);
    state = state.where((task) => task.id != taskId).toList();
  }

  /// 切换任务完成状态
  Future<void> toggleTaskCompletion(String taskId) async {
    final taskIndex = state.indexWhere((task) => task.id == taskId);
    if (taskIndex != -1) {
      final task = state[taskIndex];
      final updatedTask = task.isCompleted
          ? task.markAsIncomplete()
          : task.markAsCompleted();
      await updateTask(updatedTask);
    }
  }

  /// 批量删除任务
  Future<void> deleteTasks(List<String> taskIds) async {
    await TaskService.deleteTasks(taskIds);
    state = state.where((task) => !taskIds.contains(task.id)).toList();
  }

  /// 批量标记为完成
  Future<void> markTasksAsCompleted(List<String> taskIds) async {
    await TaskService.markTasksAsCompleted(taskIds);
    loadTasks(); // 重新加载以获取最新状态
  }

  /// 清理旧的已完成任务
  Future<int> cleanupOldTasks() async {
    final deletedCount = await TaskService.cleanupOldCompletedTasks();
    loadTasks();
    return deletedCount;
  }

  /// 清空所有任务
  Future<void> clearAllTasks() async {
    await TaskService.deleteAllTasks();
    state = [];
  }
}

/// 搜索查询状态管理
class SearchQueryNotifier extends StateNotifier<String> {
  SearchQueryNotifier() : super('');

  void updateQuery(String query) {
    state = query;
  }

  void clearQuery() {
    state = '';
  }
}

/// 任务过滤器状态管理
enum TaskFilter { all, pending, completed, overdue, dueSoon }

class TaskFilterNotifier extends StateNotifier<TaskFilter> {
  TaskFilterNotifier() : super(TaskFilter.all);

  void setFilter(TaskFilter filter) {
    state = filter;
  }
}

/// 任务排序方式状态管理
enum TaskSortBy { createdAt, dueDate, priority, title }

class TaskSortNotifier extends StateNotifier<TaskSortBy> {
  TaskSortNotifier() : super(TaskSortBy.createdAt);

  void setSortBy(TaskSortBy sortBy) {
    state = sortBy;
  }
}

/// 选中的分类状态管理
class SelectedCategoryNotifier extends StateNotifier<String?> {
  SelectedCategoryNotifier() : super(null);

  void selectCategory(String? category) {
    state = category;
  }

  void clearSelection() {
    state = null;
  }
}

// ============================================================================
// Providers
// ============================================================================

/// 任务列表Provider
final taskProvider = StateNotifierProvider<TaskNotifier, List<TaskModel>>((
  ref,
) {
  return TaskNotifier();
});

/// 搜索查询Provider
final searchQueryProvider = StateNotifierProvider<SearchQueryNotifier, String>((
  ref,
) {
  return SearchQueryNotifier();
});

/// 任务过滤器Provider
final taskFilterProvider =
    StateNotifierProvider<TaskFilterNotifier, TaskFilter>((ref) {
      return TaskFilterNotifier();
    });

/// 任务排序Provider
final taskSortProvider = StateNotifierProvider<TaskSortNotifier, TaskSortBy>((
  ref,
) {
  return TaskSortNotifier();
});

/// 选中分类Provider
final selectedCategoryProvider =
    StateNotifierProvider<SelectedCategoryNotifier, String?>((ref) {
      return SelectedCategoryNotifier();
    });

/// 过滤后的任务列表Provider
final filteredTasksProvider = Provider<List<TaskModel>>((ref) {
  final tasks = ref.watch(taskProvider);
  final searchQuery = ref.watch(searchQueryProvider);
  final filter = ref.watch(taskFilterProvider);
  final selectedCategory = ref.watch(selectedCategoryProvider);
  final sortBy = ref.watch(taskSortProvider);

  // 应用搜索过滤
  var filteredTasks = searchQuery.isEmpty
      ? tasks
      : TaskService.searchTasks(searchQuery);

  // 应用状态过滤
  switch (filter) {
    case TaskFilter.pending:
      filteredTasks = filteredTasks.where((task) => !task.isCompleted).toList();
      break;
    case TaskFilter.completed:
      filteredTasks = filteredTasks.where((task) => task.isCompleted).toList();
      break;
    case TaskFilter.overdue:
      filteredTasks = filteredTasks.where((task) => task.isOverdue).toList();
      break;
    case TaskFilter.dueSoon:
      filteredTasks = filteredTasks.where((task) => task.isDueSoon).toList();
      break;
    case TaskFilter.all:
      break;
  }

  // 应用分类过滤
  if (selectedCategory != null) {
    filteredTasks = filteredTasks
        .where((task) => task.category == selectedCategory)
        .toList();
  }

  // 应用排序
  switch (sortBy) {
    case TaskSortBy.title:
      filteredTasks.sort((a, b) => a.title.compareTo(b.title));
      break;
    case TaskSortBy.dueDate:
      filteredTasks.sort((a, b) {
        if (a.dueDate == null && b.dueDate == null) return 0;
        if (a.dueDate == null) return 1;
        if (b.dueDate == null) return -1;
        return a.dueDate!.compareTo(b.dueDate!);
      });
      break;
    case TaskSortBy.priority:
      filteredTasks.sort((a, b) => b.priority.compareTo(a.priority));
      break;
    case TaskSortBy.createdAt:
      filteredTasks.sort((a, b) => b.createdAt.compareTo(a.createdAt));
      break;
  }

  return filteredTasks;
});

/// 任务统计Provider
final taskStatisticsProvider = Provider<Map<String, int>>((ref) {
  ref.watch(taskProvider); // 监听任务变化
  return TaskService.getTaskStatistics();
});

/// 所有分类Provider
final categoriesProvider = Provider<List<String>>((ref) {
  ref.watch(taskProvider); // 监听任务变化
  return TaskService.getAllCategories();
});

/// 所有标签Provider
final tagsProvider = Provider<List<String>>((ref) {
  ref.watch(taskProvider); // 监听任务变化
  return TaskService.getAllTags();
});
